import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler


def predict(feature_test, model, features, save_path='./预测结果.csv'):
    """改进后的预测函数，包含完整结果保存"""
    if not model:
        print("模型未正确初始化")
        return None

    try:
        # 特征校验与数据准备
        missing_features = set(features) - set(feature_test.columns)
        if missing_features:
            raise ValueError(f"缺失特征: {missing_features}")

        # 提取必要字段
        X_test = feature_test[features].astype(float)
        current_price = feature_test['close']  # 获取现价

        # 标准化处理
        X_test_scaled = model.scaler_.transform(X_test)

        # 生成预测
        pred = model.predict(X_test_scaled)
        pred_proba = model.predict_proba(X_test_scaled)[:, 1]
        print(pred)
        # 构建结果DataFrame
        results = pd.DataFrame({
            'date': feature_test.index.strftime('%Y-%m-%d'),  # 日期格式化
            'current_price': current_price,  # 当前价格
            'next_day_up_prob': pred_proba,  # 次日上涨概率
            'signal': pred,  # 交易信号
            'confidence': np.abs(pred_proba - 0.5) * 2  # 置信度计算（0-1区间）
        })

        # 保存结果
        if save_path:
            results.to_csv(save_path, index=False)
            print(f"\n预测结果已保存至：{save_path}")

        # 控制台输出最新3条结果
        print("\n最新预测结果：")
        print(results.tail(3).to_string(index=False, float_format=lambda x: f"{x:.2%}"))

        return pred

    except Exception as e:
        print(f"预测失败: {str(e)}")
        return None
